package kr.co.bettersoft.pushchat.activity;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import kr.co.bettersoft.pushchat.common.CommonConstant;
import kr.co.bettersoft.pushchat.common.CommonUtil;
import kr.co.bettersoft.pushchat.common.PushChatRest;
import kr.co.bettersoft.pushchat.domain.PushChatChat;
import kr.co.bettersoft.pushchat.domain.PushChatFriend;
import kr.co.bettersoft.pushchat.domain.PushChatMember;
import kr.co.bettersoft.pushchat.domain.PushChatUser;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

/**
 * MemberInfoActivity
 *  멤버 상세 정보보기
 *   상단 이름(아이디). 왼쪽 닫기 버튼
 *   프로필 사진
 *   성별 :  / 나이 : 
 *   코멘트(스크롤 되는 텍스트)
 *   가입 일시
 *   1:1 채팅 신청 버튼
 * @author blue
 *
 */
public class MemberInfoActivity extends Activity{
	String TAG = "MemberInfoActivity";

	final int REST_SELECT_MEMBER_INFORMATION = 302;		// RestSelectMemberInformation  // 멤버 상세 정보
	final int REST_SELECT_DUPLICATION_FRIEND = 303;		// RestSelectDuplicationFriend  // 친구 등록 전 중복 검사
	final int REST_REGISTER_FRIEND = 304;				// RestRegisterFriend	// 친구 등록
	final int REST_UPDATE_DEACTIVE_FRIEND = 305;		// RestUpdateDeactivateFriend	// 친구 비활성
	final int REST_REGISTER_CHAT_AND_REGISTER_USER = 306;		// RestRegisterChatAndRegisterUser	// 1:1 채팅 신청

	// qr
	String userId;		// 사용자 아이디
	// 설정 파일 저장소  - 사용자 전번 읽기 / 쓰기 용도	
	SharedPreferences sharedPrefCustom;
	// 중복 실행 방지용
	int isUpdating = 0;
	/////////////////////////////////////////////////////////////////////////////

	TextView member_info_title ;	// 타이틀	
	Button topNaviCloseBtn; 		// 상단 닫기 버튼

	View memberInfoMasterView;		// 전체 - > 한번에 보여주기 위함

	ImageView prImage;		// 이미지
	TextView member_info_sex_txt;					// 성별
	TextView member_info_age_txt;					// 나이대
	TextView member_info_comment_txt;					// 커멘트
	TextView member_info_register_date_txt;					// 가입일자

	Button member_info_add_friend_btn;		// 친구 추가 버튼
	Button member_info_delete_friend_btn;		// 친구 끊기 버튼
	Button member_info_request_chatting_btn;		// 채팅 신청 버튼

	// 진행바
	ProgressBar pb1;		// 중단 로딩 진행바

	// 서버 통신
	String certiResult="";
	PushChatRest pushChatRest;
	String callResult = "";

	PushChatMember pushChatMember;	// 멤버 정보
	PushChatChat pushChatChat;			// 채팅방 정보

	String memberId;
	Boolean isMyFriend = false;			// 친구 등록 여부

	/////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// 핸들러
	Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg){
			try{
				Bundle b = msg.getData();		// 받아온결과를 화면에 뿌려준다.
				if(b.getInt("showYN")==1){
					// merchantData 에서 데이터 꺼내어 화면에 세팅한다.			// titleImg , name , companyName , phone , addr , pr ,,

					hidePb();

					member_info_title.setText(pushChatMember.getNickName()+"("+pushChatMember.getMemberId()+")");

					if(pushChatMember.getComment().length()>0){
						member_info_comment_txt.setText(pushChatMember.getComment());
					}
					if(pushChatMember.getGender().length()>0){
						member_info_sex_txt.setText(pushChatMember.getGender());
					}
					if(pushChatMember.getAge().length()>0){
						member_info_age_txt.setText(pushChatMember.getAge());
					}
					if(pushChatMember.getRegisterDate().length()>0){
						member_info_register_date_txt.setText(getString(R.string.reg_date_colon)+pushChatMember.getRegisterDate());
					}
					if(pushChatMember.getProfileImage()!=null){
						//  이미지 가져와서 붙임
						prImage.setImageBitmap(pushChatMember.getProfileImage());
					}else{
						prImage.setBackgroundDrawable(getResources().getDrawable(R.drawable.empty_member));
					}
					memberInfoMasterView.setVisibility(View.VISIBLE);

					if(memberId.equals(userId)){
						member_info_add_friend_btn.setVisibility(View.GONE);
						member_info_delete_friend_btn.setVisibility(View.GONE);
					}else{
						if(isMyFriend){		// 친구면 친구 끊기 버튼이 보임
							member_info_add_friend_btn.setVisibility(View.GONE);
							member_info_delete_friend_btn.setVisibility(View.VISIBLE);
						}else{				// 친구 아니면 친구 추가 버튼이 보임
							member_info_delete_friend_btn.setVisibility(View.GONE);
							member_info_add_friend_btn.setVisibility(View.VISIBLE);
						}
					}
				}
				if(b.getInt("updateFriendBtn")==1){
					// 친구 여부에 따라 친구 추가, 친구끊기 버튼을 보여준다. 자신과는 친구관계가 없다.
					if(memberId.equals(userId)){
						member_info_add_friend_btn.setVisibility(View.GONE);
						member_info_delete_friend_btn.setVisibility(View.GONE);
					}else{
						if(isMyFriend){		// 친구면 친구 끊기 버튼이 보임
							member_info_add_friend_btn.setVisibility(View.GONE);
							member_info_delete_friend_btn.setVisibility(View.VISIBLE);
						}else{				// 친구 아니면 친구 추가 버튼이 보임
							member_info_delete_friend_btn.setVisibility(View.GONE);
							member_info_add_friend_btn.setVisibility(View.VISIBLE);
						}
					}
				}
				if(b.getInt("confirmAddOrDeleteFriend")==1){					 // 친구 추가 확인
					new AlertDialog.Builder(returnThis())
					.setTitle(CommonConstant.alertTitle)							
					.setMessage(b.getString("msg"))
					.setIcon(R.drawable.ic_dialog_img)		  
					.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							handler.sendEmptyMessage(REST_REGISTER_FRIEND);
						}})
						.setNegativeButton(android.R.string.no, null).show();
				}else if(b.getInt("confirmAddOrDeleteFriend")==2){					 // 친구 끊기 확인 
					new AlertDialog.Builder(returnThis())
					.setTitle(CommonConstant.alertTitle)							
					.setMessage(b.getString("msg"))
					.setIcon(R.drawable.ic_dialog_img)		 
					.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							handler.sendEmptyMessage(REST_UPDATE_DEACTIVE_FRIEND);
						}})
						.setNegativeButton(android.R.string.no, null).show();
				}
				if(b.getInt("showAlert")==1){					 // 알림 및 경고창 . 
					new AlertDialog.Builder(returnThis())
					.setTitle(CommonConstant.alertTitle)							
					.setMessage(b.getString("msg"))
					.setIcon(R.drawable.ic_dialog_img)		// 경고창.  
					.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							// 그냥 사용자 확인 용이기 때문에 추가 조작 없음.
						}})
						.setNegativeButton("", null).show();
				}
				if(b.getInt("showAlertAndGoChatRoom")==1){					 // 알림 및 경고창 . 
					new AlertDialog.Builder(returnThis())
					.setTitle(CommonConstant.alertTitle)							
					.setMessage(b.getString("msg"))
					.setIcon(R.drawable.ic_dialog_img)		// 경고창.  
					.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							Intent intent = new Intent(MemberInfoActivity.this, ChatRoomActivity.class);
							intent.putExtra("idChat", pushChatChat.getIdChat());			// 채팅방 고유 번호. = ? 방금만들었는데 어떻게 암.
							intent.putExtra("owner", pushChatChat.getOwner());				// 이건 내 아이디(채팅방 방장 아이디)		
							startActivity(intent);
						}})
						.setNegativeButton("", null).show();
				}

				if(b.getInt("order")==1){ 		// 프로그래스바 실행
					pb1.setVisibility(View.VISIBLE);
				}else if(b.getInt("order")==2){ // 프로그래스바  종료
					pb1.setVisibility(View.INVISIBLE);
				}
				if(b.getInt("showErrToast")==1){
					Toast.makeText(MemberInfoActivity.this, R.string.error_message, Toast.LENGTH_SHORT).show();
				}

				switch (msg.what)
				{
				//					// 멤버 상세 정보 가져오기
				case REST_SELECT_MEMBER_INFORMATION   : runOnUiThread(new RunnableSelectMemberInformation());			
				break;
				//					// 친구 등록 전 중복 검사
				case REST_SELECT_DUPLICATION_FRIEND   : runOnUiThread(new RunnableSelectDuplicationFriend());			
				break;
				//					// 친구 등록
				case REST_REGISTER_FRIEND   : runOnUiThread(new RunnableRegisterFriend());			
				break;
				//					// 친구 비활성
				case REST_UPDATE_DEACTIVE_FRIEND   : runOnUiThread(new RunnableUpdateDeactivateFriend());			
				break;
				//					// 1:1 채팅 신청	
				case REST_REGISTER_CHAT_AND_REGISTER_USER   : runOnUiThread(new RunnableRegisterChatAndRegisterUser());			
				break;
				default : 
					break;
				}	
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	};

	//////////////////////////////////////////////////////////////////////////////////////////////////////////


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature( Window.FEATURE_NO_TITLE );		// no title
		setContentView(R.layout.member_info_activity);

		pushChatRest = new PushChatRest();

		member_info_title = (TextView)findViewById(R.id.member_info_title);		// 타이틀

		memberInfoMasterView = (View)findViewById(R.id.member_info_master_view);		// 마스터 뷰

		prImage = (ImageView)findViewById(R.id.prImage);


		member_info_sex_txt = (TextView)findViewById(R.id.member_info_sex_txt);
		member_info_age_txt = (TextView)findViewById(R.id.member_info_age_txt);
		member_info_comment_txt = (TextView)findViewById(R.id.member_info_comment_txt);
		member_info_register_date_txt = (TextView)findViewById(R.id.member_info_register_date_txt);


		topNaviCloseBtn = (Button) findViewById(R.id.top_navi_close_btn);
		// 상단 닫기 버튼
		topNaviCloseBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Log.d(TAG,"topNaviCloseBtn clicked");
				finish();
			}
		});


		member_info_add_friend_btn = (Button) findViewById(R.id.member_info_add_friend_btn);
		// 친구 추가 버튼
		member_info_add_friend_btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Log.d(TAG,"member_info_add_friend_btn clicked");
				confirmAddFriend();
			}
		});
		member_info_delete_friend_btn = (Button) findViewById(R.id.member_info_delete_friend_btn);
		// 친구 끊기 버튼
		member_info_delete_friend_btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Log.d(TAG,"member_info_delete_friend_btn clicked");
				confirmDeleteFriend();
			}
		});
		member_info_request_chatting_btn = (Button) findViewById(R.id.member_info_request_chatting_btn);
		// 채팅 신청 버튼
		member_info_request_chatting_btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Log.d(TAG,"member_info_request_chatting_btn clicked");
				if(!memberId.equals(userId)){		// 자신과는 금지
					handler.sendEmptyMessage(REST_REGISTER_CHAT_AND_REGISTER_USER);		 // ### 
				}
			}
		});


		// progress bar
		pb1 = (ProgressBar) findViewById(R.id.member_info_pb);		// 로딩(중앙)



		//		showPb();

		// prefs
		sharedPrefCustom = getSharedPreferences(CommonConstant.prefName,				
				Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE);
		userId = sharedPrefCustom.getString("userId", "");	

		// *** 데이터 전달 받기
		Intent gottenIntent = getIntent();
		memberId = gottenIntent.getStringExtra("memberId");

		if(isUpdating==0){
			handler.sendEmptyMessage(REST_SELECT_DUPLICATION_FRIEND);	// 친구 여부부터 확인하고 친구 정보 가져오도록 한다
			//			handler.sendEmptyMessage(REST_SELECT_MEMBER_INFORMATION);

		}
	}

	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	////////////////////////////////////////////////////////////////////////////////////////////
	// 비동기 통신.

	/**
	 * 러너블. 멤버 상세 정보를 가져온다.
	 */
	class RunnableSelectMemberInformation implements Runnable {
		public void run(){
			new backgroundSelectMemberInformation().execute();
		}
	}
	/**
	 * 비동기로 멤버 상세 정보를 가져온다.
	 * backgroundSelectMemberInformation
	 */
	public class backgroundSelectMemberInformation extends  AsyncTask<Void, Void, Void> { 
		@Override protected void onPostExecute(Void result) {  
		} 
		@Override protected void onPreExecute() {  
		} 
		@Override protected Void doInBackground(Void... params) {  
			Log.d(TAG,"backgroundSelectMemberInformation");

			if(isUpdating==0){
				isUpdating = 1;
				// 파리미터 세팅
				PushChatMember pushChatMemberParam = new PushChatMember();
				pushChatMemberParam.setMemberId(memberId);
				// 호출
				showPb();
				callResult = pushChatRest.RestSelectMemberInformation(pushChatMemberParam, returnThis());		

				// 결과 처리
				if(callResult.equals("F")){		
					showMSG();
				}else{														 
					CommonUtil commonUtil = new CommonUtil();
					Date tempDate = new Date();
					try {
						JSONObject jsonObject = new JSONObject(callResult);		// member
						pushChatMember = new PushChatMember();
						pushChatMember.setMemberId(jsonObject.getString("memberId"));
						if(pushChatMember.getMemberId()==null || pushChatMember.getMemberId().length()<1){
							pushChatMember.setMemberId("");
						}
						pushChatMember.setNickName(jsonObject.getString("nickName"));
						if(pushChatMember.getNickName()==null || pushChatMember.getNickName().length()<1){
							pushChatMember.setNickName("");
						}
						pushChatMember.setComment(jsonObject.getString("comment"));
						if(pushChatMember.getComment()==null || pushChatMember.getComment().length()<1){
							pushChatMember.setComment("");
						}
						pushChatMember.setProfileImageUrl(jsonObject.getString("profileImageUrl"));
						if(pushChatMember.getProfileImageUrl()==null || pushChatMember.getProfileImageUrl().length()<1){
							pushChatMember.setProfileImageUrl("");
						}else{
							//  이미지 가져와서 붙임
							try{
								Bitmap bmp = LoadImage(pushChatMember.getProfileImageUrl());
								pushChatMember.setProfileImage(bmp);
							}catch(Exception e){
								e.printStackTrace();
							}
						}
						pushChatMember.setGender(jsonObject.getString("gender"));
						if(pushChatMember.getGender()==null || pushChatMember.getGender().length()<1){
							pushChatMember.setGender("");
						}
						pushChatMember.setEmail(jsonObject.getString("email"));
						if(pushChatMember.getEmail()==null || pushChatMember.getEmail().length()<1){
							pushChatMember.setEmail("");
						}
						pushChatMember.setAge(jsonObject.getString("age"));
						if(pushChatMember.getAge()==null || pushChatMember.getAge().length()<1){
							pushChatMember.setAge("");
						}
						//					pushChatMember.setRegisterDate(jsonObject.getString("registerDate"));
						String tempRegisterDate = jsonObject.getString("registerDate");
						// 형변환 작업
						tempDate = commonUtil.sf.parse(tempRegisterDate);
						//							commonUtil.context = context;

						String year =  getString(R.string.year);
						String month =  getString(R.string.month);
						String day =  getString(R.string.day);
						String hour =  getString(R.string.hour);
						String minute =  getString(R.string.minute);
						SimpleDateFormat sfGeneral = new SimpleDateFormat("yyyy"+year+" MM"+month+" dd"+day+" a hh"+hour+" mm"+minute);
						SimpleDateFormat sfGeneral2 = new SimpleDateFormat("yyyy"+year+" MM"+month+" dd"+day+" HH"+hour+" mm"+minute);
						SimpleDateFormat sfGeneralChat = new SimpleDateFormat("MM"+month+" dd"+day+" a hh"+hour+" mm"+minute);

						tempRegisterDate = sfGeneral.format(tempDate);
						pushChatMember.setRegisterDate(tempRegisterDate);
						if(pushChatMember.getRegisterDate()==null || pushChatMember.getRegisterDate().length()<1){
							pushChatMember.setRegisterDate("");
						}
						pushChatMember.setPhoneNumber(jsonObject.getString("phoneNumber"));
						if(pushChatMember.getPhoneNumber()==null || pushChatMember.getPhoneNumber().length()<1){
							pushChatMember.setPhoneNumber("");
						}
						pushChatMember.setCountryCode(jsonObject.getString("countryCode"));
						if(pushChatMember.getCountryCode()==null || pushChatMember.getCountryCode().length()<1){
							pushChatMember.setCountryCode("");
						}
						pushChatMember.setLanguageCode(jsonObject.getString("languageCode"));
						if(pushChatMember.getLanguageCode()==null || pushChatMember.getLanguageCode().length()<1){
							pushChatMember.setLanguageCode("");
						}
						pushChatMember.setLatitude(jsonObject.getString("latitude"));
						if(pushChatMember.getLatitude()==null || pushChatMember.getLatitude().length()<1){
							pushChatMember.setLatitude("");
						}
						pushChatMember.setLongitude(jsonObject.getString("longitude"));
						if(pushChatMember.getLongitude()==null || pushChatMember.getLongitude().length()<1){
							pushChatMember.setLongitude("");
						}
						pushChatMember.setLocation(jsonObject.getString("location"));
						if(pushChatMember.getLocation()==null || pushChatMember.getLocation().length()<1){
							pushChatMember.setLocation("");
						}
						pushChatMember.setOpenLocationYn(jsonObject.getString("openLocationYn"));
						if(pushChatMember.getOpenLocationYn()==null || pushChatMember.getOpenLocationYn().length()<1){
							pushChatMember.setOpenLocationYn("");
						}
						pushChatMember.setPersonalityType(jsonObject.getString("personalityType"));
						if(pushChatMember.getPersonalityType()==null || pushChatMember.getPersonalityType().length()<1){
							pushChatMember.setPersonalityType("");
						}
						pushChatMember.setDeviceType(jsonObject.getString("deviceType"));
						if(pushChatMember.getDeviceType()==null || pushChatMember.getDeviceType().length()<1){
							pushChatMember.setDeviceType("");
						}
						pushChatMember.setRegistrationId(jsonObject.getString("registrationId"));
						if(pushChatMember.getRegistrationId()==null || pushChatMember.getRegistrationId().length()<1){
							pushChatMember.setRegistrationId("");
						}
						pushChatMember.setReceiveNotificationYn(jsonObject.getString("receiveNotificationYn"));
						if(pushChatMember.getReceiveNotificationYn()==null || pushChatMember.getReceiveNotificationYn().length()<1){
							pushChatMember.setReceiveNotificationYn("");
						}
					} catch (Exception e) {
						//						callResult = "F";
						showMSG();
					}
					////					processMerchantStoreInfoData();	// 화면에 뿌려준다.	
					//					pushChatMember = pushChatRest.getPushChatMember();

					if(pushChatMember.getGender().equals("MALE")){
						pushChatMember.setGender(getString(R.string.male));
					}else if(pushChatMember.getGender().equals("FEMALE")){
						pushChatMember.setGender(getString(R.string.female));
					}else if(pushChatMember.getGender().equals("ETC")){
						pushChatMember.setGender(getString(R.string.etc));
					}else if(pushChatMember.getGender().equals("N/A")){
						pushChatMember.setGender(getString(R.string.privated));
					}

					if(pushChatMember.getAge().equals("N/A")){
						pushChatMember.setAge(getString(R.string.privated));
					}
					showInfo();
				}
				hidePb();

				isUpdating = 0;
			}else{
				Log.d(TAG,"already updating..");
			}

			return null; 
		}
	}



	/**
	 * 러너블. 친구 등록 전 중복 검사 
	 */
	class RunnableSelectDuplicationFriend implements Runnable {
		public void run(){
			new backgroundSelectDuplicationFriend().execute();
		}
	}
	/**
	 * 비동기로 친구 등록 전 중복 검사
	 * backgroundSelectDuplicationFriend
	 */
	public class backgroundSelectDuplicationFriend extends  AsyncTask<Void, Void, Void> { 
		@Override protected void onPostExecute(Void result) {  
		} 
		@Override protected void onPreExecute() {  
		} 
		@Override protected Void doInBackground(Void... params) {  
			Log.d(TAG,"backgroundSelectDuplicationFriend");

			if(isUpdating==0){
				isUpdating = 1;
				// 파리미터 세팅
				PushChatFriend pushChatFriendParam = new PushChatFriend();
				pushChatFriendParam.setMemberId(memberId);		// 친구 아이디?    // ### 확실하지 않음
				pushChatFriendParam.setPushChatMemberMemberId(userId);	// 내 아이디?

				// 호출
				showPb();
				callResult = pushChatRest.RestSelectDuplicationFriend(pushChatFriendParam);		 
				hidePb();
				// 결과 처리
				if(callResult.equals("0")){			// 0 / n / F
					// 친구 아님.
					isMyFriend = false;
				}else if(callResult.equals("F")){	// 에러														 
					showMSG();
				}else{		// 1  : 친구
					isMyFriend = true;
				}
				isUpdating = 0;

				handler.sendEmptyMessage(REST_SELECT_MEMBER_INFORMATION);
			}else{
				Log.d(TAG,"already updating..");
			}
			return null; 
		}
	}


	/**
	 * 러너블.   친구 등록
	 */
	class RunnableRegisterFriend implements Runnable {
		public void run(){
			new backgroundRegisterFriend().execute();
		}
	}
	/**
	 * backgroundRegisterFriend
	 *  비동기로 친구 등록	
	 *
	 * @param
	 * @param
	 * @return
	 */
	public class backgroundRegisterFriend extends   AsyncTask<Void, Void, Void> {
		@Override protected void onPostExecute(Void result) { 
		}
		@Override protected void onPreExecute() { 
		}
		@Override protected Void doInBackground(Void... params) { 
			Log. d(TAG,"backgroundRegisterFriend");

			//			// 파리미터 세팅
			PushChatFriend pushChatFriendParam = new PushChatFriend();

			// 파라미터에 넣을 값 모르므로 일단 대기
			pushChatFriendParam.setMemberId(memberId);				// 친구 아이디
			pushChatFriendParam.setCategory("");				// 카테고리
			pushChatFriendParam.setPushChatMemberMemberId(userId);	// 내 아이디

			// 호출
			showPb();
			callResult = pushChatRest.RestRegisterFriend(pushChatFriendParam);		

			//			// 결과 처리		 
			if(callResult.equals("SUCCESS")){ // 친구 등록 성공 	 
				//				recommendationEntriesFn = pushChatRest.getWaitingRecommendationEntriesFn();
				// 보여지는 버튼 변경.
				isMyFriend = true;
				updateFriendBtn();
			}else{
				showMSG();
			}
			//			showReviewInfo();	// 리뷰 보여주기.	// ... @@ 
			hidePb();
			return null ;
		}
	}
	/**
	 * 러너블.  친구 비활성
	 */
	class RunnableUpdateDeactivateFriend implements Runnable {
		public void run(){
			new backgroundUpdateDeactivateFriend().execute();
		}
	}
	/**
	 * backgroundUpdateDeactivateFriend
	 *  비동기로  친구 비활성
	 *
	 * @param
	 * @param
	 * @return
	 */
	public class backgroundUpdateDeactivateFriend extends   AsyncTask<Void, Void, Void> {
		@Override protected void onPostExecute(Void result) { 
		}
		@Override protected void onPreExecute() { 
		}
		@Override protected Void doInBackground(Void... params) { 
			Log. d(TAG,"backgroundSelectDuplicationMemberRecommendation");
			//			// 파리미터 세팅
			PushChatFriend pushChatFriendParam = new PushChatFriend();
			// 파라미터 모르므로 일단 대기
			pushChatFriendParam.setMemberId(memberId);								// 친구 아이디
			pushChatFriendParam.setPushChatMemberMemberId(userId);	// 내 아이디
			// 호출
			showPb();
			callResult = pushChatRest.RestUpdateDeactivateFriend(pushChatFriendParam);		
			//			// 결과 처리		 
			if(callResult.equals("SUCCESS")){ // 친구 삭제 성공, 0		//  || callResult.equals("D")
				// 보여지는 버튼 변경.
				isMyFriend = false;
				updateFriendBtn();
				//				isFirstReview = true;
			}else{
				showMSG();
				//				isFirstReview = false;
			}
			hidePb();
			return null ;
		}
	}
	/**
	 * 러너블.  1:1 채팅 신청
	 */
	class RunnableRegisterChatAndRegisterUser implements Runnable {
		public void run(){
			new backgroundRegisterChatAndRegisterUser().execute();
		}
	}
	/**
	 * backgroundRegisterChatAndRegisterUser
	 *  비동기로   1:1 채팅 신청
	 *
	 * @param
	 * @param
	 * @return
	 */
	public class backgroundRegisterChatAndRegisterUser extends   AsyncTask<Void, Void, Void> {
		@Override protected void onPostExecute(Void result) { 
		}
		@Override protected void onPreExecute() { 
			showPb();
		}
		@Override protected Void doInBackground(Void... params) { 
			Log. d(TAG,"backgroundRegisterChatAndRegisterUser");
			//			// 파리미터 세팅
			PushChatChat pushChatChatParam = new PushChatChat();
			pushChatChatParam.setIp("");					// 사용자 IP. 빈값
			pushChatChatParam.setOwner(userId);				// 채팅방 생성자. 내 아이디?		
			pushChatChatParam.setMemberId(userId);			// 생성된 방에 나를 추가함.

			// 호출
			// 1차로 방을 만들고, 나를 추가함.
			callResult = pushChatRest.RestRegisterChatAndRegisterUser(pushChatChatParam);	
			//			// 결과 처리		 
			if(!(callResult.equals("F"))){ // 1:1 채팅 신청 성공
				//				 pushChatChat = pushChatRest.getPushChatChat();
				try {
					JSONObject jsonObject = new JSONObject(callResult);
					callResult = jsonObject.getString("result").toString(); 
					if(callResult.equals("SUCCESS")){
						pushChatChat = new PushChatChat();	
						pushChatChat.setIdChat(jsonObject.getString("idChat").toString());
						pushChatChat.setOwner(jsonObject.getString("owner").toString());
					}
				} catch (Exception e) {
					callResult = "F";
					e.printStackTrace();
				}

				if(!(callResult.equals("F"))){
					// 2차로 방에 상대방을 추가함.
					PushChatUser pushChatUserParam = new PushChatUser();
					pushChatUserParam.setMemberId(memberId);
					pushChatUserParam.setPushChatChatIdChat(pushChatChat.getIdChat());
					pushChatUserParam.setPushChatChatOwner(pushChatChat.getOwner());
					callResult = pushChatRest.RestRegisterUser(pushChatUserParam);	
				}
				/*
				 *  RestRegisterUser//
						,"result":"SUCCESS",}
				 */
				if(callResult.equals("SUCCESS")){
					// 3차로 채팅방 정보를 받아온다.	
					pushChatChatParam.setOwner(pushChatChat.getOwner());
					callResult = pushChatRest.RestSelectChatInformation(pushChatChatParam);
					if(!(callResult.equals("F"))){
						//						pushChatChat = pushChatRest.getPushChatChat();		// {"idChat":"88","owner":"test01",
						try {
							JSONObject jsonObject = new JSONObject(callResult);
							pushChatChat.setIdChat(jsonObject.getString("idChat").toString());
							pushChatChat.setOwner(jsonObject.getString("owner").toString());
						} catch (Exception e) {
							callResult = "F";
							e.printStackTrace();
						}
					}
				}else{
					callResult = "F";
				}
				if(callResult.equals("F")){
					showAlert(getString(R.string.create_chat_room_fail));
				}else{
					showAlertAndGoChatRoom(getString(R.string.create_chat_room_success));	
				}
			}else{
				showMSG();
			}
			hidePb();
			return null ;
		}
	}

	/////////////////////////////////////////////////////////////////////////////////////////////////////////
	// 가맹점 이미지 URL 에서 이미지 받아와서 도메인에 저장하는 부분.
	/**
	 * LoadImage
	 *  이미지 URL 에서 이미지 받아온 스트림을 비트맵으로 저장한다
	 *
	 * @param $imagePath
	 * @param
	 * @return bm
	 */
	private Bitmap LoadImage( String $imagePath ) {
		InputStream inputStream = OpenHttpConnection( $imagePath ) ;
		Bitmap bm = BitmapFactory.decodeStream( inputStream ) ;
		return bm;
	}
	/**
	 * OpenHttpConnection
	 *  이미지 URL 에서 이미지 받아와서 스트림으로 저장한다
	 *
	 * @param $imagePath
	 * @param
	 * @return stream
	 */
	private InputStream OpenHttpConnection(String $imagePath) {
		// TODO Auto-generated method stub
		InputStream stream = null ;
		try {
			URL url = new URL( $imagePath ) ;
			HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection() ;
			urlConnection.setRequestMethod( "GET" ) ;
			urlConnection.connect() ;
			if( urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK ) {
				stream = urlConnection.getInputStream() ;
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			Log.w(TAG,"MalformedURLException");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.w(TAG,"IOException");
		}
		return stream ;
	}


	/*
	 * Bitmap 이미지 리사이즈 -- xml 자체 설정으로 대체
	 * Src : 원본 Bitmap
	 * newHeight : 새로운 높이
	 * newWidth : 새로운 넓이
	 * 참고 소스 : http://skyswim42.egloos.com/3477279 ( webview 에서 capture 화면 resizing 하는 source 도 있음 )
	 */
	private BitmapDrawable BitmapResizePrc(Bitmap Src, float newHeight, float newWidth)
	{
		BitmapDrawable Result = null;
		int width = Src.getWidth();
		int height = Src.getHeight();

		// calculate the scale - in this case = 0.4f
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;

		// createa matrix for the manipulation
		Matrix matrix = new Matrix();

		// resize the bit map
		matrix.postScale(scaleWidth, scaleHeight);

		// rotate the Bitmap 회전 시키려면 주석 해제!
		//matrix.postRotate(45);

		// recreate the new Bitmap
		Bitmap resizedBitmap = Bitmap.createBitmap(Src, 0, 0, width, height, matrix, true);

		// check
		width = resizedBitmap.getWidth();
		height = resizedBitmap.getHeight();
		//		Log.i("ImageResize", "Image Resize Result : " + Boolean.toString((newHeight==height)&&(newWidth==width)) );

		// make a Drawable from Bitmap to allow to set the BitMap
		// to the ImageView, ImageButton or what ever
		Result = new BitmapDrawable(resizedBitmap);
		return Result;
	}

	////////////////////////////////////////////////////////////////////////////////////////////////////////
	// 유틸

	/**
	 * confirmAddFriend
	 *  친구 추가 확인 받기
	 *
	 * @param
	 * @param
	 * @return
	 */
	public void confirmAddFriend(){			 		
		new Thread(
				new Runnable(){
					public void run(){
						Message message = handler.obtainMessage();				
						Bundle b = new Bundle();
						b.putInt("confirmAddOrDeleteFriend", 1);
						b.putString("msg", getString(R.string.confirm_reg_friend));
						message.setData(b);
						handler.sendMessage(message);
					}
				}
		).start();
	} 
	/**
	 * confirmDeleteFriend
	 *  친구 끊기 확인받기
	 *
	 * @param
	 * @param
	 * @return
	 */
	public void confirmDeleteFriend(){			 
		new Thread(
				new Runnable(){
					public void run(){
						Message message = handler.obtainMessage();				
						Bundle b = new Bundle();
						b.putInt("confirmAddOrDeleteFriend", 2);
						b.putString("msg", getString(R.string.confirm_del_friend));
						message.setData(b);
						handler.sendMessage(message);
					}
				}
		).start();
	} 
	/**
	 * updateFriendBtn
	 *  친구 여부에 따라 보여지는 버튼 다르게. 
	 *
	 * @param
	 * @param
	 * @return
	 */
	public void updateFriendBtn(){			 
		new Thread(
				new Runnable(){
					public void run(){
						Message message = handler.obtainMessage();				
						Bundle b = new Bundle();
						b.putInt("updateFriendBtn", 1);
						message.setData(b);
						handler.sendMessage(message);
					}
				}
		).start();
	} 



	/**
	 * returnThis
	 *  컨택스트를 리턴한다
	 *
	 * @param
	 * @param
	 * @return
	 */
	public Context returnThis(){
		return this;
	}
	/**
	 * showMSG
	 *  화면에 error 토스트 띄운다
	 *
	 * @param
	 * @param
	 * @return
	 */
	public void showMSG(){			// 화면에 error 토스트 띄움..
		new Thread(
				new Runnable(){
					public void run(){
						Message message = handler.obtainMessage();				
						Bundle b = new Bundle();
						b.putInt("showErrToast", 1);
						message.setData(b);
						handler.sendMessage(message);
					}
				}
		).start();
	} 

	/**
	 * showAlert
	 * 얼럿창을 띄운다
	 *
	 * @param msg
	 * @param 
	 * @return 
	 */
	public void showAlert(final String msg){
		MemberInfoActivity.this.runOnUiThread(new Runnable(){		 
			@Override
			public void run(){
				Message message = handler.obtainMessage();				
				Bundle b = new Bundle();
				b.putInt("showAlert", 1);
				b.putString("msg", msg);			// 화면에 보여줄 메시지
				message.setData(b);
				handler.sendMessage(message);
			}
		});
	}
	/**
	 * showAlertAndGoChatRoom
	 * 얼럿창을 띄운다
	 *
	 * @param msg
	 * @param 
	 * @return 
	 */
	public void showAlertAndGoChatRoom(final String msg){
		MemberInfoActivity.this.runOnUiThread(new Runnable(){		 
			@Override
			public void run(){
				Message message = handler.obtainMessage();				
				Bundle b = new Bundle();
				b.putInt("showAlertAndGoChatRoom", 1);
				b.putString("msg", msg);			// 화면에 보여줄 메시지
				message.setData(b);
				handler.sendMessage(message);
			}
		});
	}

	// 중앙 프로그래스바 보임, 숨김
	/**
	 * showPb
	 *  중앙 프로그래스바 가시화한다
	 *
	 * @param
	 * @param
	 * @return
	 */
	public void showPb(){
		new Thread( 
				new Runnable(){
					public void run(){
						Message message = handler .obtainMessage();
						Bundle b = new Bundle();
						b.putInt( "order" , 1);
						message.setData(b);
						handler .sendMessage(message);
					}
				}
		).start();
	}
	/**
	 * hidePb
	 *  중앙 프로그래스바 비가시화한다
	 *
	 * @param
	 * @param
	 * @return
	 */
	public void hidePb(){
		new Thread(
				new Runnable(){
					public void run(){
						Message message = handler .obtainMessage();
						Bundle b = new Bundle();
						b.putInt( "order" , 2);
						message.setData(b);
						handler .sendMessage(message);
					}
				}
		).start();
	}

	// 화면에 보여준다..
	/**
	 * showInfo
	 *  받아온 정보를 화면에 보여준다.
	 *
	 * @param
	 * @param
	 * @return
	 */
	public void showInfo(){
		new Thread(
				new Runnable(){
					public void run(){
						Message message = handler.obtainMessage();
						Bundle b = new Bundle();
						b.putInt("showYN", 1);
						message.setData(b);
						handler.sendMessage(message);
					}
				}
		).start();
	}
	///////////////////////////////////////////////////////////////////////////////////////////////////////
}